#!/usr/bin/env python

# pytexipng, Creates a png image from LaTeX code
#
# Copyright (C) 2006 Sebastian Lara Menares <slara@udec.cl>
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51 Franklin
# St, Fifth Floor, Boston, MA 02110-1301 USA

import pygtk
pygtk.require("2.0")
import gtk
import gtk.glade
import os

class AppGui:
    def __init__(self):
	

	# Libglade XML 
	self.wTree = gtk.glade.XML(os.path.join(os.path.dirname(__file__),'pytexipng.glade'))
	
	view = create_view(self)
	
	scrollwin = self.wTree.get_widget('scroll')
	self.prefs = self.wTree.get_widget('pref_dialog')
	self.save_dialog = self.wTree.get_widget('fileselection1')
	self.image = self.wTree.get_widget('image1')
	self.window = self.wTree.get_widget('window1')
	view.show()
	scrollwin.add(view)
	scrollwin.show()
	
	sensitive = 0
	self.save = self.wTree.get_widget('save')
	self.saveas = self.wTree.get_widget('save_as')
	self.saveas.set_sensitive(sensitive)
	self.save.set_sensitive(sensitive)
	self.num = 0

	# Set Output Filename
	self.save_dialog.set_current_folder(os.environ['HOME'])
	self.save_dialog.set_current_name('form.png')
	
	
	dic = { "on_button1_clicked"	    :   self.button1_clicked,   \
		"on_button2_clicked"	    :   self.button2_clicked,   \
		"on_button3_clicked"	    :   self.button3_clicked,   \
		"on_button4_clicked"	    :   self.button4_clicked,   \
		"on_button5_clicked"	    :	self.save_file,		\
		"dialog_close_window"	    :   (gtk.main_quit),	\
		"on_close_dialog"	    :   self.close_dialog,	\
		"on_save_activate"	    :   self.save_file,	        \
		"on_save_as_activate"	    :	self.save_as,		\
		"on_salir1_activate"	    :	(gtk.main_quit),	\
		"on_about_activate"	    :	self.about}

	self.wTree.signal_autoconnect (dic)
	
	return

## CALLBACKS
    def button1_clicked(self, widget):
	
	# Get Text from SourceBuffer
	start, end = self.buffer.get_bounds()   
	equation = self.buffer.get_text(start,end)

	# Create Temp TeX code
	entry = self.wTree.get_widget('entry1')
	environment = entry.get_text()
		
	tex = tex_template % { 'env' :  environment, 'eqn' : equation}
	print tex
	
	if self.num:
	    self.save.set_sensitive(1)
	self.saveas.set_sensitive(1)
	
	pic_create(self,tex)
	self.image.set_from_file('/tmp/texipng.png')
	self.image.show()

    def button2_clicked(self, widget): 
	self.prefs.run()
    
    def close_dialog(self, widget, event):
	widget.hide()
	return True

    def button3_clicked(self, widget):
	self.prefs.hide()
	return True

    def button4_clicked(self, widget):
	try:
	    filename = os.path.basename(self.initial_filename)
	    self.save_dialog.set_current_name(filename)
	except:
	    self.save_dialog.set_current_name('form.png')
	
	self.save_dialog.hide()
	return True

    def save_as(self, widget):
	self.initial_filename = self.save_dialog.get_filename()
	self.save_dialog.show()
	self.num = 1		    # Once we name the output file with `Save As',
				    # the `save' gtk.MenuItem is activated
	return True

    def save_file(self, widget):
	image_filename = self.save_dialog.get_filename()
	copy_comm = 'cp /tmp/texipng.png ' + image_filename
	os.system(copy_comm)
	self.save.set_sensitive(0)
	try: 
	    self.save_dialog.hide()
	except:
	    pass
	return True

    def about(self, widget):
	dialog = AboutDialog(self.window)
	dialog.run()
	dialog.destroy()


def create_view(self):
    """Checks if there is gtksourceview, else, we use  GtkTextView"""
    
    try:
	import gtksourceview
	lm = gtksourceview.SourceLanguagesManager()
	self.buffer = gtksourceview.SourceBuffer()
	self.buffer.set_data('languages-manager', lm)
	manager = self.buffer.get_data('languages-manager')
	mime_type = 'text/x-tex'
	language = manager.get_language_from_mime_type(mime_type)
	self.buffer.set_highlight(True)
	self.buffer.set_language(language)
	view = gtksourceview.SourceView(self.buffer)
	view.set_show_line_numbers(True)
	
    except:
	view = gtk.TextView()
	self.buffer = view.get_buffer()    
    
    return view

class AboutDialog(gtk.AboutDialog):
    def __init__(self, parent):
        gtk.AboutDialog.__init__(self)
        self.set_transient_for(parent)
        self.set_name('Pytexipng')
        self.set_copyright(u'Copyright \u00A9 2006 Sebastian Lara Menares')
        self.set_authors(('Sebastian Lara Menares <slaramen@gmail.com>',))


def pic_create(self,tex):
    """Create TeX File"""

    file = open('/tmp/texipng.tex','w')
    
    file.write(tex)
    file.close()
    spin = self.wTree.get_widget('spinbutton1')
    resolution = spin.get_value_as_int()
    

    command1 = 'latex -interaction=nonstopmode /tmp/texipng.tex'		# TODO Warn on LaTeX Errors
    os.system(command1)
    command2 = 'dvipng -T tight -D ' + repr(resolution) + ' -o /tmp/texipng.png' + ' texipng.dvi' 
    os.system(command2)
    os.system('rm texipng.aux;rm texipng.log;rm texipng.dvi')			# TODO Need a log dialog for errors

tex_template = r'''\documentclass[fleqn]{article}
\usepackage{amssymb,amsmath}
\usepackage[latin1]{inputenc}
\begin{document}
\thispagestyle{empty} \mathindent0cm \parindent0cm
\begin{%(env)s} 
%(eqn)s
\end{%(env)s}
\end{document}
'''

app = AppGui()
gtk.main()
